<!--
  * 实训室耗材审批管理
  *
  * @Author:    王俊权
  * @Date:      2024-11-06 10:32:23
  * @Copyright  🐂🐎bloc
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="审批表ID" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.id" placeholder="审批表ID" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="showForm" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
              <ExcelUpload></ExcelUpload>

            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table

            :dataSource="tableData"
            :columns="columns"
            rowKey="id"
            :scroll="{x:2900}"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column }">

	    <!-- 有图片预览时 注释解开并把下面的'picture'修改成自己的图片字段名即可 -->
              <!-- <template v-if="column.dataIndex === 'picture'">
                  <FilePreview :fileList="text" type="picture" />
                </template> -->

	    <!-- 使用字典时 注释解开并把下面的'dict'修改成自己的字典字段名即可 有多个字典字段就复制多份同理修改 不然不显示字典 -->
              <!-- 方便修改tag的颜色 orange green purple success processing error default warning -->
              <!-- <template v-if="column.dataIndex === 'dict'">
                <a-tag color="cyan">
                  {{ text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '暂无' }}
                </a-tag>
              </template> -->

              <template v-if="column.dataIndex === 'approvalStatus'">
                <div >
                  <a-tag v-if="record.approvalStatus == 1" color="green">已批准</a-tag>
                  <a-tag  v-else-if="record.approvalStatus == 0" color="blue" >待审核</a-tag>
                  <a-tag  v-else-if="record.approvalStatus == 2" color="red" >已驳回</a-tag>
                </div>
              </template>


                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate" style="display: flex">
                        <a-button @click="showForm(record)" type="link">编辑</a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                        <a-button @click="onAccept(record)" v-if="isEnableApproval(record).value "  type="link" v-privilege="'consu:approval:query'">
                        审批 </a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

        <ConsumablesPurchaseApprovalForm  ref="formRef" @reloadList="queryData"/>
        <consumables-purchase-approval-accept-form ref="acceptRef" @reloadList="queryData"/>
    </a-card>
</template>
<script setup>
import {reactive, ref, onMounted, h, computed} from 'vue';
import {message, Modal, Tag} from 'ant-design-vue';
    import { SmartLoading } from '/src/components/framework/smart-loading';
    import { consumablesPurchaseApprovalApi } from '/@/api/business/consumables-purchase-approval/consumables-purchase-approval-api';
    import { PAGE_SIZE_OPTIONS } from '/src/constants/common-const';
    import { smartSentry } from '/src/lib/smart-sentry';
    import TableOperator from '/src/components/support/table-operator/index.vue';
    import ConsumablesPurchaseApprovalForm from './consumables-purchase-approval-form.vue';
    import ConsumablesPurchaseApprovalAcceptForm from './consumables-purchase-approval-accept-form.vue'
    import {useUserStore} from "/@/store/modules/system/user.js";
    import ExcelUpload from "/@/components/mycomponents/excelupload/index.vue";
    //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件

    // ---------------------------- 表格列 ----------------------------
    const approvalObj = {
      agreed:{
        title: '已通过',
        attrs:{
          color:'green'
        }
      },
      disagreed:{
        title: '已驳回',
        attrs:{
          color:'red'
        }
      },
      pending:{
        title: '待审核',
        attrs:{
          color:'blue'
        }
      }
    }
    const columns = ref([
        {
            title: '序号',
            ellipsis: true,
            customRender: ({text, record, index}) => {
                return (queryForm.pageNum - 1) * queryForm.pageSize + index + 1;
            },
        },
        {
            title: '采购日期',
            dataIndex: 'purchaseDate',
            ellipsis: true,
        },
        {
            title: '请购部门',
            dataIndex: 'department',
            ellipsis: true,
        },
        {
            title: '申请人',
            dataIndex: 'actualName',
            ellipsis: true,
        },
        {
            title: '申请人电话',
            dataIndex: 'applicantPhone',
            ellipsis: true,
        },
      {
            title: '耗材编码',
            dataIndex:'materialCode',
            ellipsis: true,
        },
        {
            title: '耗材名称',
            dataIndex: 'materialName',
            ellipsis: true,
        },
        {
            title: '类别',
            dataIndex:'categoryName',
            ellipsis: true,
        },
        {
            title: '规格',
            dataIndex: 'specification',
            ellipsis: true,
        },
      {
            title: '单位',
        dataIndex: 'unit',
        ellipsis: true,
      },
        {
            title: '数量',
            dataIndex: 'quantity',
            ellipsis: true,
        },
        {
            title: '单价（元）',
            dataIndex: 'unitPrice',
            ellipsis: true,
            width: 120,
        },
        {
            title: '金额（元）',
            dataIndex: 'totalAmount',
            ellipsis: true,
        },
      {
            title: '采购途径',
        dataIndex: 'purchaseChannel',
        ellipsis: true,

      },
        {
            title: '存放地点',
            dataIndex: 'storageLocation',
            ellipsis: true,
        },
        {
            title: '预算采购金额',
            dataIndex: 'budgetAmount',
            ellipsis: true,
        },
        {
            title: '经费项目名称',
            dataIndex: 'projectName',
            ellipsis: true,
        },
        {
            title: '经费项目编号',
            dataIndex: 'projectId',
            ellipsis: true,
        },
      {
        title:'备注',
        dataIndex: 'remark',
        ellipsis: true,
      },
        {
            title: '使用部门副职意见',
            dataIndex: 'deputyHeadOpinion',
            ellipsis: true,
          width: 150,
          customRender: ({text, record}) => {
            return render(record.deputyHeadOpinion);
          },
        },
        {
            title: '使用部门正职意见',
            dataIndex: 'headOpinion',
            ellipsis: true,
            width: 150,
            customRender: ({text, record}) => {
            return render(record.headOpinion);
            },
        },
        {
            title: '职能部门意见',
            dataIndex: 'functionDepartmentOpinion',
            ellipsis: true,
            customRender: ({text, record}) => {
              if(Number(record.budgetAmount) > 20000){
                return render(record.functionDepartmentOpinion);
              }

          },
        },
        {
            title: '教学主管领导意见',
            dataIndex: 'teachingLeaderOpinion',
            ellipsis: true,
            width: 150,
            customRender: ({text, record}) => {
            if(Number(record.budgetAmount) > 20000) {
              return render(record.teachingLeaderOpinion);
            }
          },
        },
        {
            title: '审核状态',
            dataIndex: 'approvalStatus',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 140,
          align: 'center',
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        id: undefined, //审批表ID
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);




    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await consumablesPurchaseApprovalApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);
    // ---------------------------- 审批 ----------------------------
    function render(record){
      const resolve = 0;
      const reject =  1;
      let attrs = {};
      let title = '';
      if(record == resolve) {
        title = approvalObj.disagreed.title;
        attrs =approvalObj.disagreed.attrs;
      }else if(record == reject){
        title = approvalObj.agreed.title;
        attrs =approvalObj.agreed.attrs;
      }else{
        title = approvalObj.pending.title;
        attrs =approvalObj.pending.attrs;
      }

      return h(Tag,attrs,title);
    }
//使用部部长
const positionId = ref(8)
//使用部副部长
const positionIdFu = ref(9)
//教学主管
const positionIdTea = ref(21)
//职能部门
const positionIdZhi = ref(19)
//超管
const positionIdSuper = ref(11)
console.log(useUserStore().positionId,positionIdSuper.value)
function isEnableApproval(record){
      return computed(()=>{
        switch (useUserStore().positionId){
          case positionId.value:
            return record.headOpinion == null;
          case positionIdFu.value:
            return record.deputyHeadOpinion == null;
          case positionIdTea.value:
            return record.teachingLeaderOpinion == null;
          case positionIdZhi.value:
            return record.functionDepartmentOpinion == null;
          case positionIdSuper.value:
            return isAble(record);
          default:
            return false;
        }
      })
}



    //审批
//审批
function isAble(record) {
  // 确保budgetAmount是数字
  const budgetAmount = Number(record.budgetAmount);

  console.log(record.approvalStatus, record.deputyHeadOpinion, record.headOpinion);

  // 检查 approvalStatus、deputyHeadOpinion 和 headOpinion 是否满足基本条件
  if (record.approvalStatus !== 0 || record.deputyHeadOpinion == null || record.headOpinion == null) {
    return false;
  }

  // 如果预算金额大于 20000，检查更多条件
  if (budgetAmount > 20000) {
    return record.functionDepartmentOpinion !== 0 && record.teachingLeaderOpinion !== 0;
  }

  // 如果预算金额小于等于 20000，直接返回 true
  return true;
}


// ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await consumablesPurchaseApprovalApi.delete(data.id);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await consumablesPurchaseApprovalApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    const acceptRef = ref();
    function onAccept(data){
      acceptRef.value.show(data);
    }
</script>

